import {
    HTTP_REQUEST_URL,
    HEADER,
    TOKENNAME,
    UIDNAME,
    HEADERPARAMS
} from '@/config/app';
import {
    toLogin,
    checkLogin
} from '../libs/login';
import store from '../store';


/**
 * 发送请求
 */
function baseRequest(url, method, data, {
    noAuth = false,
    noVerify = false
}, params) {
    let Url = HTTP_REQUEST_URL,
        header = HEADER
    if (params != undefined) {
        header = HEADERPARAMS;
    }
	 
    if (!noAuth) {
        //登录过期自动登录
        if (!store.state.app.token && !checkLogin()) {
            toLogin();
            return Promise.reject({
                msg: '未登录'
            });
        }
    }
    // console.log('请求method：'+method)

    // #ifdef H5
    Url = '/api'; //H5下将地址修改为/api
    // #endif
    // console.log('noVerify------',noVerify,'store.state.app.token------',store.state.app.token)
    if (!noVerify) {
        if (store.state.app.token) {
            header[TOKENNAME] = 'Bearer ' + store.state.app.token;
            header[UIDNAME] = store.state.app.uid;
        } else {
            header[TOKENNAME] = 'Bearer ' + '1639623107738';
        }
    } else {
        header[TOKENNAME] = 'Bearer ' + '1639623107738';
    }
    //mock 数据时使用
    if (url.indexOf("mock") != -1) {
        Url = '';
    }

    return new Promise((reslove, reject) => {
        uni.request({
            url: Url + url,
            method: method || 'GET',
            header: header,
            data: data || {},
            success: (res) => {
                // console.log('接口请求res---------------', res)
                if (noVerify) {
                    if (res.data.code == 200)
                        reslove(res.data, res);
                    else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
                        reslove(res.data, res);
                    } else
                        reject(res.data.msg || res.msg || '系统错误');
                } else if (res.data.code == 200)
                    reslove(res.data, res);
                else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
                    toLogin();
                    reject(res.data);
                } else
                    reject(res.data.msg || res.msg || '系统错误');
            },
            fail: (msg) => {
                reject('请求失败');
            }
        })
    });
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
    request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;